package com.example.newdatabasedemo.slice;

import com.example.newdatabasedemo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.data.distributed.common.*;
import ohos.data.distributed.device.DeviceFilterStrategy;
import ohos.data.distributed.device.DeviceInfo;
import ohos.data.distributed.user.SingleKvStore;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Context context = getApplicationContext();
        KvManagerConfig config = new KvManagerConfig(context);
        KvManager kvManager = KvManagerFactory.getInstance().createKvManager(config);
        SingleKvStore singleKvStore = null;

        Options options = new Options();
        options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
        String storeId = "MyAppDB";
        singleKvStore = kvManager.getKvStore(options, storeId);


        singleKvStore.putString("todo", "学习编程技能");
        String value = singleKvStore.getString("todo");

        Text text = findComponentById(ResourceTable.Id_text_helloworld);
        text.setText(value);
        List<ohos.data.distributed.device.DeviceInfo> deviceInfoList = kvManager.getConnectedDevicesInfo(DeviceFilterStrategy.NO_FILTER);
        List<String> deviceIdList = new ArrayList<>();
        for (DeviceInfo deviceInfo : deviceInfoList) {
            deviceIdList.add(deviceInfo.getId());
        }
        if (deviceIdList.size() > 0) {
            singleKvStore.sync(deviceIdList, SyncMode.PUSH_ONLY);
        }
        kvManager.closeKvStore(singleKvStore);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
